# coding:utf-8
__author__ = 'CAINXI'

import xlwt
from django.http import StreamingHttpResponse
from django.http import HttpResponse
from tools import sqltoExcel
import os

def export_excel():
    print "excel_export"
    # 创建 Workbook 时，如果需要写入中文，请使用 utf-8 编码，默认是 unicode 编码。
    # wb = xlwt.Workbook(encoding='utf-8')
    # ws = wb.add_sheet('配件价格')
    # ws.write(0, 0, '产品编号')
    # ws.write(0, 1, '产品名称')
    # ws.write(0, 2, '产品经理')
    # ws.write(0, 3, '产品规模')
    # ws.write(0, 4, '产品状态')
    # ws.write(0, 5, '创建时间')
    sql="select * from cm_product_info"
    wb=sqltoExcel.sqltoExcel(sql)
    # ------ 开始：这段代码可以用下面注释段替代，都是本应保存为文件格式的改成保存为数据流，以便返回前端下载
    response = HttpResponse(content_type='application/vnd.ms-excel')
    response['Content-Disposition'] = 'attachment; filename=example.xls'
    wb.save(response)
    return response


def file_upload(request):
    print "file_upload"
    filename = request.FILES["fileImport"]
    UploadedFile = request.FILES["fileImport"]
    f = UploadedFile.read()
    name = UploadedFile.name
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
    the_file_name = BASE_DIR + "/upload/" + name
    destination = open(the_file_name,'wb+')
    for chunk in UploadedFile.chunks():
        destination.write(chunk)
    destination.close()
    return HttpResponse('file_upload')

def send_email(request):
    print "send_email"
    import os
    dest= request.POST["destaddress"]
    subject=request.POST["subject"]
    body=request.POST["body"]
    # print type(body)
    fujian=request.FILES["fujianimport"] if request.FILES.has_key("fujianimport") else None

    # print type(fujian)

    # filename = request.FILES["fileImport"]
    # UploadedFile = request.FILES["fileImport"]
    # f = UploadedFile.read()
    # name = UploadedFile.name
    # BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
    # the_file_name = BASE_DIR + "/upload/" + name
    from django.core.mail import send_mail,EmailMessage
        # import os
        # BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
        # the_file_name = BASE_DIR + "/upload/"
    # attachname = fujian.temporary_file_path()
    em=EmailMessage(subject,body,'chengk@chinaetf.com.cn',to=[dest])
    if fujian:
        fujian_name=fujian._name
        em.attach(fujian_name,fujian.read())
    em.send()
    return HttpResponse('send_email')
def file_download(request):
    # do something...
    print "file_download"
    def file_iterator(file_name, chunk_size=512):
            f = open(file_name, "rb")
            while True:
                c = f.read(chunk_size)
                if c:
                    yield c
                else:
                    break
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
    filename = u"测试testfile.txt"
    the_file_name = BASE_DIR + "/upload/" + filename
    response = HttpResponse(file_iterator(the_file_name), content_type='APPLICATION/OCTET-STREAM') #设定文件头，这种设定可以让任意文件都能正确下载，而且已知文本文件不是本地打开

    response['Content-Disposition'] = 'attachment; filename='+filename.encode('utf-8')#设定传输给客户端的文件名称
    response['Content-Length'] = os.path.getsize(the_file_name)#传输给客户端的文件大小
    print response
    return response
